package com.toune.dltools

import java.lang.reflect.Field

/**

 * @Author DongLei
 * @Date 2021/2/26 0026-上午 11:32
 * @Email dong.eleven@qq.com
 */
object DLClsTool {

    fun getClz(string: String): Class<*> {
//        return Class.forName("com.toune.androidnetutil.Api")
        return Class.forName(string)
    }

    /**
     * 获取属性的值
     * @param fields
     * @return
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     */
    fun getFieldValue(obj: Any?, field: Field): String {
        val sf = StringBuffer()
        //获取属性值
        try {
            //开启反射获取私有属性值
            field.isAccessible = true
            sf.append(field.get(obj))
        } catch (e: Exception) {
            // TODO: handle exception
            e.printStackTrace()
        }
        return sf.toString()
    }

    fun getFieldValue(claName: String, field: Field): String {
        val sf = StringBuffer()
        //获取属性值
        try {
            var obj = getClz(claName)
            //开启反射获取私有属性值
            field.isAccessible = true
            sf.append(field.get(obj))
        } catch (e: Exception) {
            // TODO: handle exception
            e.printStackTrace()
        }
        return sf.toString()
    }

    /**
     * 设置 对象的 属性名+属性值
     * @param map
     * @return
     */
    fun setFieldValue(obj: Any?, field: Field, value: Any) {
        try {
            field.isAccessible = true
            field.set(obj, value)
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }
    fun setFieldValue(claName: String, field: Field, value: Any) {
        try {
            var obj = getClz(claName)
            field.isAccessible = true
            field.set(obj, value)
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }
}